package droid.frame.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import droid.frame.app.Callback;
import droid.frame.libcore.R;
import droid.frame.utils.Android;
import droid.frame.utils.android.ImmUtils;

/**
 * 条形码、
 *
 * @author coffee<br>
 *         2016-12-22上午11:29:52
 */
public class CodeLinearLayout extends LinearLayout implements TextWatcher {

    private int CODE_LENGTH = 10;
    private int codeLayout;
    // 当前对象
    private CodeLinearLayout mInputLayout;
    // 当前获取焦点的child view
    private EditText mCurrentEdit;// 当前
    // 输入完成后的回调
    private Callback callback;

    public CodeLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mInputLayout = this;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CodeLinearLayout);
        CODE_LENGTH = ta.getInt(R.styleable.CodeLinearLayout_childCount, 6);
        codeLayout = ta.getResourceId(R.styleable.CodeLinearLayout_childLayout, -1);
        ta.recycle();
        if (codeLayout != -1) {
            initChild();// 初始化控件
        }
    }

    private void initChild() {
        for (int i = 0; i < CODE_LENGTH; i++) {
            final EditText editView = (EditText) LayoutInflater.from(getContext()).inflate(codeLayout, mInputLayout, false);
            // 只有获取到光标的时候才添加TextChangedListener
            // 光标不可见, 只能通过程序设置获取焦点, 其他不可获取焦点的EditText不可点击
            editView.setOnFocusChangeListener(new OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    mCurrentEdit = (EditText) v;
                    if (hasFocus) {
                        for (int i = 0; i < mInputLayout.getChildCount(); i++) {
                            EditText child = (EditText) mInputLayout.getChildAt(i);
                            if (TextUtils.isEmpty(child.getText())) {
                                child.requestFocus();
                                break;
                            }
                        }
                    }else{
                        //需要点击其他的弹出软键盘
                        Android.showSoftInput(getContext(),mCurrentEdit);
                    }
                }
            });
            //
            editView.setOnKeyListener(new OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_DEL) {
                        return false;// true以后既不会继续传到NumEditText内部
                    }
                    return false;
                }
            });
            // click的时候把光标移到第一个为空的child
            editView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i < mInputLayout.getChildCount(); i++) {
                        EditText child = (EditText) mInputLayout.getChildAt(i);
                        if (TextUtils.isEmpty(child.getText())) {
                            child.requestFocus();
                            mCurrentEdit = child;
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Android.showSoftInput(getContext(), mCurrentEdit);
                                }
                            }, 300);
                            break;
                        }
                    }
                }
            });
            mInputLayout.addView(editView);
            editView.addTextChangedListener(this);
        }
        // 让第一个获取焦点
        EditText first = (EditText) mInputLayout.getChildAt(0);
        first.requestFocus();
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (editable.length() == 0) {
            return;
        }
        int position = mInputLayout.indexOfChild(mCurrentEdit);
        if (editable.length() <= 1) {
            boolean flag = true;
            // 判断是否从第一个空位置插入的数字
            for (int i = 0; i < CODE_LENGTH; i++) {
                EditText tmp = (EditText) mInputLayout.getChildAt(i);
                if (TextUtils.isEmpty(tmp.getText())) {
                    // 如果插入数字的edit前面还有空格, 则交换位置
                    if (i < position) {
                        flag = false;
                        mCurrentEdit.setText("");
                        tmp.setText(editable);
                        break;
                    }
                }
            }
            // 不需要移动光标
            if (flag == false) {
                return;
            } else {
                // 当前view不是最后一个元素, 处理光标 移动到下一个元素
                if ((position + 1) >= CODE_LENGTH) {
                    // 当前最后一个元素 不做处理
                } else {
                    EditText next = (EditText) mInputLayout.getChildAt(position + 1);
                    // 如果下一个元素的内容为空 ,则移动
                    if (next.getText().length() <= 0) {
                        next.requestFocus();
                    } else {
                        // 元素内容非空, 不移动光标
                    }
                }
            }
        } else {// 一个EditText输入多个数字
            EditText lastView = (EditText) mInputLayout.getChildAt(CODE_LENGTH - 1);
            // 最后一个元素满了、则禁止插入新元素
            if (lastView.length() > 0) {
                // 重置当前view的文本值----禁止输入
                mCurrentEdit.setText(editable.subSequence(0, 1));
                return;
            } else {
                // 移位
                for (int j = CODE_LENGTH - 1; j > position + 1; j--) {
                    EditText last = (EditText) mInputLayout.getChildAt(j);
                    EditText pre = (EditText) mInputLayout.getChildAt(j - 1);
                    last.setText(pre.getText());
                }
                // 重置当前view的文本值
                mCurrentEdit.setText(editable.subSequence(0, 1));
                // 当前元素是最后一个
                if (position + 1 >= CODE_LENGTH) {
                    // 不做处理
                } else {
                    // 处理下一个view的值
                    EditText next = (EditText) mInputLayout.getChildAt(position + 1);
                    next.setText(editable.subSequence(editable.length() - 1, editable.length()));
                }
            }
        }
        // 最后一个元素不为空
        EditText last = (EditText) mInputLayout.getChildAt(CODE_LENGTH - 1);
        if (callback != null && TextUtils.isEmpty(last.getText()) == false) {
            callback.execute();
        }
    }

    public String getText() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            EditText code = (EditText) mInputLayout.getChildAt(i);
            if (code.getText() == null) {
                continue;
            } else {
                sb.append(code.getText());
            }
        }
        return sb.toString();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    public void setCodeLength(int codeLength) {
        this.CODE_LENGTH = codeLength;
    }

    public Callback getCallback() {
        return callback;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }
}
